import type { PatientLoginReq } from '@/api/common';
import type { LoginPatientInfoRespVO } from '@/api/patient';
import { CommonApi } from '@/api/common';
import { SEX } from '@/enums';
import { useUserStore } from '@/store/userStore';
import { extractBirthday } from '@/utils/date.utils';
import { currRoute, withQueryString } from '@/utils/router.utils';

export function useLoginHelper() {
  const userStore = useUserStore();
  const query = currRoute().query;

  const redirectURLName = 'redirectUrl';

  const withBuildRedirectUrl = (url: string, query = {}, redirectUrl?: string) => {
    const { path: currentPath, query: currentQuery } = currRoute();
    const redirect = redirectUrl || currentQuery[redirectURLName] || currentPath || '/pages/index/index';
    return withQueryString(url, {
      ...query,
      [redirectURLName]: encodeURIComponent(redirect)
    });
  };

  const redirectLogin = (url: string, redirectUrl?: string) => {
    // 判断当前是否为待跳转页
    const { path: currentPath } = currRoute();
    if (currentPath === url) {
      return;
    }

    // 跳转登录页
    uni.navigateTo({
      url: withBuildRedirectUrl(url, {}, redirectUrl)
    });
  };

  // 登录成功跳转至指定页面
  const redirectTo = () => {
    const redirect = query[redirectURLName] || '/pages/index/index';
    uni.reLaunch({
      url: redirect,
      fail: () => {
        uni.reLaunch({
          url: '/pages/index/index'
        });
      }
    });
  };

  // 登录
  const handleLogin = (params: PatientLoginReq) => {
    return CommonApi.onPatientLogin(params).then(res => {
      userStore.setAuthStore(res.accessToken, res.refreshToken, res.logType);
      return userStore.getUserInfo();
    });
  };

  function onToLoginConfirm(res: LoginPatientInfoRespVO) {
    let { patientName: name, idCard: idno, birthday: birthDate, address, sex } = res;
    // 没有生日，根据身份证号提取
    if (!birthDate && idno) {
      birthDate = extractBirthday(idno);
    }

    const params: Record<string, any> = { name, idno, birthDate, sex: sex === SEX.MALE ? '男' : '女' };
    if (address) {
      params.address = address;
    }
    uni.navigateTo({
      url: withQueryString('/pages/login/loginConfirm', {
        ...query,
        ...params
      })
    });
  }
  return {
    handleLogin,
    redirectLogin,
    redirectTo,
    withBuildRedirectUrl,
    onToLoginConfirm
  };
}
